package com.lichen.db;

import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.net.Uri;

public class CityContentProvider extends ContentProvider {

	public static final String AUTHORITY = "com.lichen.cityprovider";
	
	private SQLiteDatabase db;
	private CityDatabaseHelper dbHelper;
	
	private static final int QUERY_NORMAL= 1;
	private static final int QUERY_BY_ID= 2;
	private  static final  int QUERY_SEARCH_CITY_NAME= 3;
	
	public static UriMatcher uriMatcher;
	static{
		uriMatcher=new UriMatcher(UriMatcher.NO_MATCH);
		
		uriMatcher.addURI(AUTHORITY,"city", QUERY_NORMAL);
		uriMatcher.addURI(AUTHORITY,"city/#", QUERY_BY_ID);
		
		uriMatcher.addURI(AUTHORITY,SearchManager.SUGGEST_URI_PATH_QUERY, QUERY_SEARCH_CITY_NAME);
		uriMatcher.addURI(AUTHORITY,SearchManager.SUGGEST_URI_PATH_QUERY + "/*", QUERY_SEARCH_CITY_NAME);
	}
	
	@Override
	public boolean onCreate() {
		dbHelper = new CityDatabaseHelper(getContext());
		return dbHelper != null;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		db = dbHelper.getReadableDatabase();
		switch (uriMatcher.match(uri)) {
		case QUERY_NORMAL:
			Cursor cursor = db.query(City.TABLE_NAME, projection,
					selection, selectionArgs, null, null, null);
			cursor.setNotificationUri(getContext().getContentResolver(), uri);
			return cursor;
		case QUERY_BY_ID:
			String rowId = uri.getLastPathSegment();
			return db.query(City.TABLE_NAME, null, "_id = ?", new String[]{rowId}, null, null, null);
		case QUERY_SEARCH_CITY_NAME:
			return dbHelper.search(selectionArgs[0]);
		default:
			throw new IllegalArgumentException("Unknown Uri: " + uri);
		}
	}

	@Override
	public String getType(Uri uri) {
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		db = dbHelper.getWritableDatabase();
		long rowId = db.insert(City.TABLE_NAME, "", values);
		if (rowId > 0) {
			Uri rowUri = ContentUris.appendId(City.CONTENT_URI.buildUpon(),
					rowId).build();
			getContext().getContentResolver().notifyChange(rowUri, null);
			return rowUri;
		}
		throw new SQLiteException("Failed to insert " + uri);
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		return 0;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		return 0;
	}

}
